/**
 * 		scanActions
 * 			
 * This file is used for functions such as: select feature 
 * 
 *	History: 	
 *   DATE 					AUTHOR 					DESCRIPTION
 * ----------------------------------------------------------------------------------------------------------
 * 24 - 01 - 2013			NguyenNV				Create new
 * 23 - 05 - 2013			NguyenNV				Update search and draw polygon
 */
var FEATURE_ID;
var ARRAY_FIRST_LAYER;
var THE_SECOND_LAYER = null;

$('#bt_tim_ok_district').click(function(){
	searchingInsideFeatures();
});
$('#bt_tim_cancel_district').click(function(){
	$("#table-content tr").remove(); 
	$(".south").hide();
});
/*
 * 
 * Function: onClicktimDiemNamTrong	 											   							
 * Parameters:
 * 		 Parameter1: Void 															 																				
 * Return:	 
 * 		 void : 
 * 
 * Description:	Display popup for searching
 * 				features inside districts 
 * 
 * Author: NGUYENNV
 * Date : 2013/01/11										   												
 * onChangeSelectLayer
 */
function onClicktimDiemNamTrong(){
	Graphic.clear();
	CurrentFunction.name = Fuctions.searchFeatureInside;
	TYPE_OF_POPUP = Popup_Type.Display_Poligon_Contain_Point;
	CommonGeo.displayPopup(LANGUAGE["finding_layer_in_layer"],'auto','auto');
}

/*
 * 
 * Function: onClickChkCtrlQuanHuyen	 											   							
 * Parameters:
 * 		 Parameter1: Void 															 																				
 * Return:	 
 * 		 void : 
 * 
 * Description:	checking one district
 * 
 * Author: NGUYENNV
 * Date : 2013/01/11										   												
 * 
 */
function onClickChkCtrlQuanHuyen(element){
	var idQuanHuyen = element.attribute;
	if(element.checked){
		ARRAY_QUANHUYEN[ARRAY_QUANHUYEN.length] = idQuanHuyen;
	}
	else CommonFuns.removeByValue(ARRAY_QUANHUYEN,idQuanHuyen);
}
/*
 * 
 * Function: onClickDetailInfor	 											   							
 * Parameters:
 * 		 Parameter1: Object 															 																				
 * Return:	 
 * 		 void : 
 * 
 * Description:	Click to view feature's detail information  
 * 
 * Author: NGUYENNV
 * Date : 2013/01/11										   												
 * 
 */
/*
 * 
 * Function: getFeatureDetailInfor	 											   							
 * Parameters:
 * 		 Parameter1: String 															 																				
 * Return:	 
 * 		 void : 
 * 
 * Description:	Getting feature's detail information
 * 
 * Author: NGUYENNV
 * Date : 2013/01/11										   												
 * 
 */
function getFeatureDetailInfor(_fid){

	IS_READING_DATA = 0;
	COMPLETED_WAITING = 0;
	var dataId = _fid.split('.');
	var assetId = dataId[0];
	var sFileJSP = "GetData.jsp";
	for ( var i = 0; i < CurrentLayer.arrAlias.length; i++) 
	{
		//if(arrField_Alias[i].LayerName == layerName){
				
		var name = CurrentLayer.arrAlias[i].Name;
			
			if(CurrentLayer.arrAlias[i].Name == "maquan")
				{
					//var districtName = CommonFuns.getDistricName(ARR_FEATURE_DETAIL_INFOR[name]);
					ARR_FEATURE_DETAIL_INFOR[name] = LANGUAGE["da_nang"];
					continue;
				}
			if(CurrentLayer.arrAlias[i].Name == "maphuong")
				{
					ARR_FEATURE_DETAIL_INFOR[name] = CommonFuns.getCommunName(ARR_FEATURE_DETAIL_INFOR[name]);
					continue;
				}
			if( CurrentLayer.arrAlias[i].IsCategory && CurrentLayer.arrAlias[i].IsShow)
				{
				
				COMPLETED_WAITING++;
					var $divMap_Data = $(document.createElement('div'));
					$divMap_Data.attr("Name", CurrentLayer.arrAlias[i].Name);
					$divMap_Data.load(
							sPortletJSP + sFileJSP + "?attr=" + CurrentLayer.arrAlias[i].FieldValue
							+"&asset="+assetId
							+"&table="+CurrentLayer.arrAlias[i].TableName,
							function(data) {
								var temp = 	$(this).attr("Name");
								var splitData = data.split('<p>');
								for ( var iItem = 0; iItem < splitData.length; iItem++) 
								{
									var splitData_Item = splitData[iItem].split('<br>');
									if (splitData_Item.length < 2) continue;
									
									if(ARR_FEATURE_DETAIL_INFOR[temp] == splitData_Item[0].replace(/^\s+|\s+$/g, "")){
										ARR_FEATURE_DETAIL_INFOR[temp] = splitData_Item[1];
									}
								}
								IS_READING_DATA++;
					});
				}
		//}
		//else continue;
	}
}
/*
 * 
 * Function: waitingDataAndDraw	 											   							
 * Parameters:
 * 		 Parameter1: Void 															 																				
 * Return:	 
 * 		 void : 
 * 
 * Description:	Waiting data from server and display result
 * 
 * Author: NGUYENNV
 * Date : 2013/01/11										   												
 * 
 */
function waitingDataAndDraw() {
	var objRead = null;
	if (COMPLETED_WAITING != IS_READING_DATA ) {
		objRead = setTimeout("waitingDataAndDraw()", 100);
	} 
	else {
		clearTimeout(objRead);
		var splitData = FEATURE_ID.split('.');
		layerName = splitData[0];
		$("#tbl_view_detail_info tr").remove();
		objTable = base.getElementById('tbl_view_detail_info');
		for ( var i = 0; i < CurrentLayer.arrAlias.length; i++) 
		{
			var name = base.trim(CurrentLayer.arrAlias[i].Name.toLowerCase());
			if(	name == base.trim("fid")
				|| name == base.trim("timecode")
				|| name == base.trim("diachiip")
				|| name == base.trim("nguoicn")
				|| name == base.trim("ngaycn")
				|| name == base.trim("ngaytao")
				|| name == base.trim("nguoitao"))
				{
					continue;
				}
			else{
				RowHeader = document.createElement('tr');
				cell0Header = document.createElement('td');
				cell0Header.className = "text-align-l";
				cell0Header.innerHTML = CurrentLayer.arrAlias[i].Alias;
				cell1Header = document.createElement('td');
				if(CurrentLayer.arrAlias[i].Name!="anhminhhoa"){
					cell1Header.className = "text-align-l";
					cell1Header.setAttribute("width","150px");
					if(CurrentLayer.arrAlias[i].IsComment){
						var text = CurrentLayer.arrAlias[i].DataType;
						if(text=="m3")text="m&sup3;/h";
						else if(text=="m2")text="m&sup2;";
						else if(text=="m3k")text="m&sup3;";
						text = " ("+text+")";
						if(ARR_FEATURE_DETAIL_INFOR[CurrentLayer.arrAlias[i].Name]==""||ARR_FEATURE_DETAIL_INFOR[CurrentLayer.arrAlias[i].Name].length==0)
							cell1Header.innerHTML = ARR_FEATURE_DETAIL_INFOR[CurrentLayer.arrAlias[i].Name];
						else
							cell1Header.innerHTML = ARR_FEATURE_DETAIL_INFOR[CurrentLayer.arrAlias[i].Name]+text;
					}else{
						cell1Header.innerHTML = ARR_FEATURE_DETAIL_INFOR[CurrentLayer.arrAlias[i].Name];
					}
					RowHeader.appendChild(cell0Header);
					RowHeader.appendChild(cell1Header);
					objTable.appendChild(RowHeader);
				}else if(CurrentLayer.arrAlias[i].Name=="anhminhhoa"){
					var value1 = ARR_FEATURE_DETAIL_INFOR[CurrentLayer.arrAlias[i].Name];
					if(value1!=""){
						var src1 = serverName + sPortletImage + "Asset/" + value1;
						var objImg = document.createElement("img");
						objImg.style.width = "100%";
						objImg.style.height = "150px";
						objImg.src = src1;
						RowHeader.appendChild(cell0Header);
						RowHeader.appendChild(objImg);
						objTable.appendChild(RowHeader);
					}
				}
			}
		}
	}
}
/*
 * 
 * Function: setFeatureIdToArray	 											   							
 * Parameters:
 * 		 Parameter1: Void 															 																				
 * Return:	 
 * 		 void : 
 * 
 * Description:	With feature id, get all attributes 
 * 
 * Author: NGUYENNV
 * Date : 2013/01/11										   												
 * 
 */
function setFeatureIdToArray(_fid){
	
	ARR_FEATURE_DETAIL_INFOR = new Array();
	var splitData = _fid.split('.');
	var _layerName = splitData[0];
	
	var layer = CommonGeo.getLayerByID(_fid);
	
	for(var i=0; i < CurrentLayer.arrAlias.length;i++ )
	{

	if(CurrentLayer.arrAlias[i].LayerName == _layerName)
		{
			value = CommonGeo.getFeatureById(layer,_fid).attributes[CurrentLayer.arrAlias[i].Name];
			if(value == null) value = "";
			ARR_FEATURE_DETAIL_INFOR[CurrentLayer.arrAlias[i].Name] = value;
		}
	}
}
/*
 * 
 * Function: searchingInsideFeatures	 											   							
 * Parameters:
 * 		 Parameter1: Void 															 																				
 * Return:	 
 * 		 void : 
 * 
 * Description:	Searching features inside polygons 
 * 
 * Author: NGUYENNV
 * Date : 2013/01/11										   												
 * 
 */
function searchingInsideFeatures(){
	ScanFeature.create();
	if(ARRAY_FIRST_LAYER.length > 0 && THE_SECOND_LAYER != null)
	{			
		for(var j = 0 ; j < ARRAY_QUANHUYEN.length ; j++)
		{
			for(var i = 0 ; i < ARRAY_FIRST_LAYER.length ; i++)
			{
				var layerInside = CommonGeo.getLayerByIdLayer(ARRAY_FIRST_LAYER[i]);
				for(var k=0 ; k < layerInside.features.length ; k++ )
				{
					var geom = layerInside.features[k].geometry;
					var geomType = CommonGeo.getTypeOfGeometry(ARRAY_FIRST_LAYER[i]);
					if(geomType == Geometries.Polyline)
					{
						var bool = CommonGis.isLineInCommuneSearch(geom,ARRAY_QUANHUYEN[j]);
						if(bool)
						{
							ScanFeature.insert(layerInside.features[k].fid);
						}
					}
					else if(CommonGis.isPointInCommune(geom,ARRAY_QUANHUYEN[j]))
					{
					    ScanFeature.insert(layerInside.features[k].fid);
					}
				}
				
			}
		}
	}else{
		alert(LANGUAGE["NotYetChoiceLayer"]);
	}
	if(ScanFeature.arrayFid.length > 0){
		ScanFeature.display(ARRAY_FIRST_LAYER[0]);
		$("#footer-page").show();
	}
	else
		alert(LANGUAGE["no_result"]);
}
/*
 * 
 * Function: getFeatureInsidePolygon	 											   							
 * Parameters:
 * 		 Parameter1: Void 															 																				
 * Return:	 
 * 		 void : 
 * 
 * Description:	get list of features when drawing a polygon 
 * 
 * Author: NGUYENNV
 * Date : 2013/01/11										   												
 * 
 */
function getFeatureInsidePolygon(){
	ScanFeature.arrayFid = [];
	for(var i=0; i < mapWFS.length; i++)
		if(mapWFS[i].LayerId == "giss_b_quan_huyen"
			||mapWFS[i].LayerId == "giss_b_xa_phuong")
			continue;
		else
			{
				var geomType = mapWFS[i].Geometry_Type;
				var layerTemp = CommonGeo.getLayerByIdLayer(mapWFS[i].LayerId);
				if(layerTemp!=null){
					for(var j = 0; j < layerTemp.features.length; j++)
					{
						var geomTemp = layerTemp.features[j].geometry;
						for(var k=0; k < ScanFeature.arrayGeom.length; k++)
							{
								var geom = ScanFeature.arrayGeom[k];
								if(geomType == Geometries.Point)
								{
									if(geom.containsPoint(geomTemp))
									{
										ScanFeature.arrayFid[ScanFeature.arrayFid.length] = layerTemp.features[j].fid;
									}
								}
								else if(geomType == Geometries.Polyline)
									{
										
										if(CommonGeo.isLineInPolygon(geom, geomTemp))
											{
												ScanFeature.arrayFid[ScanFeature.arrayFid.length] = layerTemp.features[j].fid;
											}
										
									}
								else if(geomType == Geometries.Polygon)
									{
										if(geom.intersects(geomTemp))
											{
												ScanFeature.arrayFid[ScanFeature.arrayFid.length] = layerTemp.features[j].fid;	
											}
									}
							}
					}
				}
			}
}

SearchingAction = {
		
		comboQuanHuyen:function(_ComboQ){
			var optionContrl1 = document.createElement("option");
			optionContrl1.value = -1;
			optionContrl1.innerHTML = LANGUAGE["da_nang"];
			optionContrl1.selected = "selected";
			_ComboQ.appendChild(optionContrl1);
			for(var i=0; i< vectorDistricts.features.length; i++)
			{
					var optionContrl = document.createElement("option");
					optionContrl.value = arrFeatureDistrict[i].fid;
					optionContrl.innerHTML = arrFeatureDistrict[i].attributes["name_vn"];
					_ComboQ.appendChild(optionContrl);
			}
		},
		/*
		 * 
		 * Function: getFidInsideOneLayer	 											   							
		 * Parameters:
		 * 		 Parameter1: geom 		
		 * 		 Parameter2: string 	
		 * 		 Parameter3: array 																 																				
		 * Return:	 
		 * 		 void : 
		 * 
		 * Description:	Getting list of feature id inside layer
		 * 
		 * Author: NGUYENNV
		 * Date : 2013/01/11										   												
		 * 
		 */
		getFidInsideOneLayer:function(_coverLayerGeom, layerTemp, _array){
			
				if(layerTemp.features.length > 0)
					{
					for(var i=0 ; i < layerTemp.features.length; i++)
						{
							var pointGeom = layerTemp.features[i].geometry;
							
								if(_coverLayerGeom.intersects(pointGeom))
								{
									_array[_array.length] = layerTemp.features[i].fid;
									layerTemp.drawFeature(layerTemp.features[i], "select");
									//layerTemp.drawFeature(layerTemp.features[i], "default");
								}
								else continue;
					
						}
					}
			
			return 1;
		},
		onChangeDistrict:function(ctrl){
			var idValue = ctrl.value;
			THE_SECOND_LAYER = idValue;
			ARRAY_QUANHUYEN = new Array();
			ARRAY_QUANHUYEN[ARRAY_QUANHUYEN.length] = idValue;
			var _bounds = null;
			var featureAction = null;
			for(var i=0;i<vectorCommune.features.length;i++){
				var feature = vectorCommune.features[i];
				if(feature.attributes["com_id"]==idValue){
					featureAction = feature;
					break;
				}
			}
			if(featureAction != null)
			{
				if (_bounds == null)
					_bounds = featureAction.geometry.getBounds().clone();
					_bounds.extend(featureAction.geometry.getBounds());
				if (_bounds != null)
						map.zoomToExtent(_bounds, false);
			}
		},
		/*
		 * 
		 * Function: onClickChkCtrl	 											   							
		 * Parameters:
		 * 		 Parameter1: Void 															 																				
		 * Return:	 
		 * 		 void : 
		 * 
		 * Description:	event click select a asset 
		 * 
		 * Author: NGUYENNV
		 * Date : 2013/01/11										   												
		 * 
		 */
		onClickChkCtrl: function(element){
			var idlayer = element.attribute;
			COMBO_ID_LAYER = idlayer;
			ARRAY_FIRST_LAYER = new Array();
			ARRAY_FIRST_LAYER[ARRAY_FIRST_LAYER.length] = idlayer;
			/*if(element.checked){
			ARRAY_FIRST_LAYER[ARRAY_FIRST_LAYER.length] = idlayer;
			}
			else CommonFuns.removeByValue(ARRAY_FIRST_LAYER,idlayer);*/
		},
		drawListOfAsset:function(_div){
			base.removeChildDiv(_div);
			var objTable = document.createElement("table");
			objTable.border="0";
			_div.appendChild(objTable);
			ARRAY_FIRST_LAYER = new Array();
			for(var i=0 ; i< mapWFS.length ; i++)
			{
				if(mapWFS[i].Visible
						&& (mapWFS[i].Geometry_Type == Geometries.Polyline 
							|| mapWFS[i].Geometry_Type == Geometries.Point )){
					
					var objTR = document.createElement("tr");
					var objTDck = document.createElement("td");
					objTDck.setAttribute("width","10%");
					objTDck.align = "center";
					objTDck.style.padding = "5px 5px 5px 5px";
					var inputFld = document.createElement('input');
					inputFld.type = "radio"; 
					inputFld.name = "assetindistrict";
					inputFld.attribute = mapWFS[i].LayerId;
				   	inputFld.id = "idCheckBoxPointSelection"+mapWFS[i].LayerId;
				   	inputFld.attribute = mapWFS[i].LayerId;
				    inputFld.setAttribute("onClick","SearchingAction.onClickChkCtrl(this)");
				   	objTDck.appendChild(inputFld);
					var objTD = document.createElement("td");
					objTD.setAttribute("width","70%");
					objTD.innerHTML = mapWFS[i].Layer_Name;
					objTR.appendChild(objTDck);
					objTR.appendChild(objTD);
					objTable.appendChild(objTR);
				}
				else continue;
				
			}
		}
};
/*
 * 
 * Function: onChangeSelectLayer	 											   							
 * Parameters:
 * 		 Parameter1: Void 															 																				
 * Return:	 
 * 		 void : 
 * 
 * Description:	onChange when selecting layer
 * 
 * Author: NGUYENNV
 * Date : 2013/01/11										   												
 * 
 */
function onChangeSelectLayer(){
	var LayerID = this.value ;
	if(LayerID != -1)
		{
			CurrentLayer.create();
			CurrentLayer.layerId = LayerID;
			CurrentLayer.arrAlias = CommonGeo.setCurrentAlias(LayerID);
			var resultArr = new Array();
			resultArr = ScanFeature.getListForDisplay(LayerID);
			if(resultArr.length > 0)
				Graphic.displayList(resultArr);
			else alert(LANGUAGE["no_result"]);
		}
	else{
			Graphic.clearContent();
	}
}

ScanFeature = {
		layer : 	  null,
		control: 	  null,
		oldFeature: 	  null,
		arrayFid: 	  null,
		arrayLayerid: null,
		arrayGeom: 	  null,
		IsScan: 	  false, // on/off
		indexLayer: 	0,
		arrayFeatureId:null,
		create:function(){
			this.layer = null;
			this.control = null;
			this.arrayFid = new Array();
			this.arrayLayerid = new Array();
			this.IsScan = true;
			this.arrayGeom = new Array();
			this.arrayFeatureId = new Array();
		},
		close:function(){
			var div1 = base.getElementById(DivObject.DIV_SEARCH_BY_DRAW_POLYGONE);
			var div2 = base.getElementById(DivObject.DIV_SEARCH_INSIDE_DISTRICT);
			var div3 = base.getElementById(DivObject.DIV_SEARCH_BY_SELECTION);
			if(div1 != null)
				base.removeChildDiv(div1);
			if(div2 != null)
				div2.style.display = "none";
			if(div3 != null)
				div3.style.display = "none";
			$(".south").hide();
			$(".search_attribute").hide();
		},
		closeDrawPolygone:function(){
			if(ScanFeature.control != null)
			{
				ScanFeature.removeAllFeatures();
				ScanFeature.control.deactivate();
			}
			MapAction.HideWFSAll();
		},
		drawPolygon:function(isActive){
			MapAction.DeActive();
			if(ScanFeature.control!=null) map.removeControl(ScanFeature.control);
			if(ScanFeature.layer != null) map.destroy();
	    	ScanFeature.layer = new OpenLayers.Layer.Vector("Polygon Layer");
	    	map.addLayers([ScanFeature.layer]);
	    	ScanFeature.control = new OpenLayers.Control.DrawFeature(
	    			ScanFeature.layer
	    			,OpenLayers.Handler.Polygon
	    			,{
	    				featureAdded: this.featureAdded,
	    				handlerOptions: {holeModifier: "altKey"}
	    			});
	    	
	    	map.addControl(ScanFeature.control);   
	    	ScanFeature.control.activate();
		},
		drawPolygonMain:function(_divContent){
			var div = base.getElementById(_divContent);
			base.removeChildDiv(div);
			div.style.display = "block";
			var label = document.createElement("label");
			label.innerHTML = LANGUAGE["selectLayerForDisplay"];
			div.appendChild(label);
			var objTable = document.createElement("table");
			objTable.border="2";
			
			div.appendChild(objTable);
			for(var i=0 ; i< this.arrayLayerid.length ; i++)
			{
				if(this.arrayLayerid[i] == LANGUAGE["tabl_phuongxa"]
					|| this.arrayLayerid[i] == LANGUAGE["table_quan_huyen"])
					continue;
				else
					{
						var Layer = CommonGeo.getLayerByIdLayer(this.arrayLayerid[i]);
						var radioInput = document.createElement("input");
						radioInput.type = "radio";
						radioInput.name = "drawpolygone";
						radioInput.value = this.arrayLayerid[i];
						radioInput.setAttribute("onclick","ScanFeature.drawPolygonOnClick(this);");
						radioInput.innerHTML = Layer.name;
						var TR_Object = document.createElement("tr");
						var TD_object = document.createElement("td");
						TD_object.style.padding = "5px 5px 5px 5px";
						var TD_object1 = document.createElement("td");
						TD_object.setAttribute("width","10%");
						TD_object.align = "center";
						TD_object1.innerHTML = Layer.name;
						TD_object.appendChild(radioInput);
						TR_Object.appendChild(TD_object);
						TR_Object.appendChild(TD_object1);
						objTable.appendChild(TR_Object);
					}
				
			}
		},
		drawPolygonOnClick:function(element){
			var LayerID = element.value ;
			if(LayerID != -1)
			{
				CurrentLayer.create();
				CurrentLayer.layerId = LayerID;
				COMBO_ID_LAYER = LayerID;
				CurrentLayer.arrAlias = CommonGeo.setCurrentAlias(LayerID);
				var resultArr = new Array();
				resultArr = ScanFeature.getListForDisplay(LayerID);
				if(resultArr.length > 0)
					{
						ScanFeature.getFeatureIdByFid(resultArr);
						$("#table-content tr").remove(); 
						$(".south").show();
						Graphic.init();
						Graphic.isShowView = true;
						Graphic.divPaging = base.getElementById('footer-page');
						Graphic.tableContent = "table-content";
						Graphic.displayList(resultArr);
						Graphic.waitingData();
						Graphic.drawFooter();
						ScanFeature.exportExcel();
						$("#footer-page").show();
					}
				else alert(LANGUAGE["no_result"]);
			}
		},
		/**feature added action */
	    featureAdded: function(fes)
	    {
	    	ScanFeature.arrayGeom[ScanFeature.arrayGeom.length] = fes.geometry;
	    	getFeatureInsidePolygon();
			ScanFeature.setListLayer();
			ScanFeature.drawPolygonMain(DivObject.DIV_SEARCH_BY_DRAW_POLYGONE);
			//ScanFeature.display();
	    },
	    /** select polygon action */
	    SelectPoly : function(indexLayer)
	    {
	    	MapAction.DeActive();
	    	if(ScanFeature.control!=null) map.removeControl(ScanFeature.control);
	    	if(ScanFeature.layer != null) map.destroy();
	    	//var indexLayer = selectToolCboLayers[selectToolCboLayers.selectedIndex].value;
	    	var _arrayNew = null;
	    	if(indexLayer!=0)_arrayNew = map.layers[indexLayer];
	    	//else _arrayNew = CommonGeo.getmapWFSArray(mapWFS);
	    	ScanFeature.control = new OpenLayers.Control.SelectFeature(
	    			_arrayNew, {
	    				clickout : true,
	    				toggle : false,
	    				multiple : false,
	    				hover : false,
	    				toggleKey : "ctrlKey",
	    				multipleKey : "shiftKey",
	    				box : isDrawBox,
	    				onSelect : this.SelectedFeature,
	    				onUnselect: this.UnselectFeature
	    			});
	    	map.addControl(ScanFeature.control);    	
	    	ScanFeature.control.activate();
	    },
	    /** unselect feature action */
	    UnselectFeature:function(fes)
	    {
	    	ScanFeature.remove(fes.fid);
	    },
	    /** select feature action */
	    SelectedFeature : function(fes)
	    {
	    	ScanFeature.insert(fes.fid);
	    	ScanFeature.setListLayer();
	    	var layer =  vectorArray[ScanFeature.indexLayer-numBaseLayer];
			ScanFeature.display(layer.LayerId);
	    },
		insert:function(_fid){
			CommonFuns.insertToArray(_fid, this.arrayFid);
			//alert(this.arrayFid.length);
		},
		remove:function(_fid){
			CommonFuns.removeByValue(this.arrayFid,_fid);
			//alert(this.arrayFid.length);
		},
		/*
		 * 
		 * Function: setListLayer	 											   							
		 * Parameters:
		 * 		 Parameter1: Void 															 																				
		 * Return:	 
		 * 		 void : 
		 * 
		 * Description:	Setting list of layers 
		 * 
		 * Author: NGUYENNV
		 * Date : 2013/01/11										   												
		 * 
		 */
		setListLayer:function(){
			
			var arrayLayer = new Array();
			for(var i=0 ; i < ScanFeature.arrayFid.length; i++)
			{
				 var splitData = ScanFeature.arrayFid[i].split('.');
				 if(!CommonFuns.isExistItem(arrayLayer,splitData[0]))
					CommonFuns.insertToArray(splitData[0], arrayLayer);
			}
			this.arrayLayerid = arrayLayer;
		},
		/*
		 * 
		 * Function: getListForDisplay	 											   							
		 * Parameters:
		 * 		 Parameter1: Void 															 																				
		 * Return:	 
		 * 		 void : 
		 * 
		 * Description:	Getting list of feature with layer id 
		 * 
		 * Author: NGUYENNV
		 * Date : 2013/01/11										   												
		 * 
		 */
		getListForDisplay:function(_layerID){
			var _arrayTemp = new Array();
			for(var i=0; i < this.arrayFid.length ; i++)
				{
					var splitData = this.arrayFid[i].split('.');
					if(splitData[0] == _layerID)
						_arrayTemp[_arrayTemp.length] = this.arrayFid[i];
				}
			return _arrayTemp;
		},
		/*
		 * 
		 * Function: removeAllFeatures	 											   							
		 * Parameters:
		 * 		 Parameter1: Void 															 																				
		 * Return:	 
		 * 		 void : 
		 * 
		 * Description:	Remove all features 
		 * 
		 * Author: NGUYENNV
		 * Date : 2013/01/11										   												
		 * 
		 */
		removeAllFeatures:function()
		{
			if(this.layer != null)
				{
					this.layer.removeAllFeatures();
					this.arrayGeom = [];
				}
		},
		onChangeSelectLayer:function(ctrl)
		{
			var south = $(".south");
			south.hide();
			ScanFeature.indexLayer = ctrl.value;
			COMBO_ID_LAYER = vectorArray[ScanFeature.indexLayer].LayerId;
			if( ScanFeature.indexLayer !=0 ){
				ScanFeature.create();
				//if(drawPolygon)
				ScanFeature.SelectPoly(ctrl.value);
			}
			else{
				if(ScanFeature.control!=null)ScanFeature.control.deactivate();
				var south = $(".south");
				south.hide();
				var div = base.getElementById(DivObject.DIV_CONTENT_LISTASSET_BY_SELECTION);
				base.removeChildDiv(div);
			}
		},
		display:function(_layerID){
			if(_layerID != -1)
			{
				$("#divMapLoading").show();
				CurrentLayer.create();
				CurrentLayer.layerId = _layerID;
				CurrentLayer.arrAlias = CommonGeo.setCurrentAlias(_layerID);
				var resultArr = ScanFeature.getListForDisplay(_layerID);
				if(resultArr.length > 0)
				{
					ScanFeature.getFeatureIdByFid(resultArr);
					$("#table-content tr").remove(); 
					$(".south").show();
					$("#content_list_bongden").empty();
					Graphic.init();
					Graphic.isShowView = true;
					Graphic.divPaging = base.getElementById('footer-page');
					Graphic.tableContent = "table-content";
					Graphic.displayList(resultArr);
					Graphic.clear();
					var objTable = base.getElementById(Graphic.tableContent);
					objTable.setAttribute("bordercolor",COLOR_BORDER);
					objTable.border="1";
					objTable.style.width="100%";
					Graphic.drawFeaturesHeaderTable(objTable, CurrentLayer.layerId);
					Graphic.drawBodyTable(objTable,ARR_LAYER_RESULT);
					Graphic.drawFooter();
					ScanFeature.exportExcel();
				}
				else{
					$("#divMapLoading").hide();
					alert(LANGUAGE["no_result"]);
				}
			}
		},
		exportExcel:function(){
			$('#iddownloadexcel').hide();
			var sFileJSP = "ExportExcel.jsp";
			// Get excel file name
			var fileName = SearchingAttribute.createFileName()+".xls";
			var realPath =  $('#txtRealPath').val()+fileName;
			$('#iddownloadexcel').attr("href", realPath);
			var arrResult = JSON.stringify(ScanFeature.arrayFeatureId);
			$.ajax({
				url: sPortletJSP + sFileJSP,
			    type: "POST",
			    data: {
			        myArray : arrResult,
			        layerId: CurrentLayer.layerId,
			        filename: fileName
			    },
		        success: function(data) {
		        	var result = data.trim();
		        	if(result == "0")
		        		$('#iddownloadexcel').hide();
		        	else {
		        		$('#iddownloadexcel').show();
		        	}
		        	$("#divMapLoading").hide();
		        }
			});
		},
		getFeatureIdByFid:function(arrFid){
			ScanFeature.arrayFeatureId = new Array();
			var layer = CurrentLayer.layerId;
			var vector = LayerTool.getLayerFromLayerID(layer);
			var colum = getFieldColumnKey(layer);
			for(var j=0;j<arrFid.length;j++){
				var id = arrFid[j];
				for(var i=0;i<vector.features.length;i++){
					var feature = vector.features[i];
					if(feature.fid==id){
						ScanFeature.arrayFeatureId[ScanFeature.arrayFeatureId.length]=feature.attributes[colum];
					}
				}
			}
		},
		
		/****************/
		/*lich su su co */
		/****************/
		onChangeSelectLayerSuCo1:function(ctrl)
		{
			var south = $(".south");
			south.hide();
			ScanFeature.indexLayer = ctrl.value;
			
			if( ScanFeature.indexLayer !=0 ){
				ScanFeature.create();
				ScanFeature.SelectPolySuCo(ctrl.value);
			}
			else{
				if(ScanFeature.control!=null)ScanFeature.control.deactivate();
				
				var div = base.getElementById(DivObject.DIV_CONTENT_LISTASSET_BY_SELECTION);
				base.removeChildDiv(div);
			}
		},
		
		/** select polygon action */
		SelectPolySuCo1 : function(indexLayer)
	    {
	    	MapAction.DeActive();
	    	if(ScanFeature.control!=null) map.removeControl(ScanFeature.control);
	    	if(ScanFeature.layer != null) map.destroy();
	    	var _arrayNew = null;
	    	if(indexLayer!=0)_arrayNew = map.layers[indexLayer];
	    	map.layers[indexLayer].setVisibility(true);
	    	ScanFeature.control = new OpenLayers.Control.SelectFeature(
	    			_arrayNew, {
	    				clickout : true,
	    				toggle : false,
	    				multiple : false,
	    				hover : false,
	    				toggleKey : "ctrlKey",
	    				multipleKey : "shiftKey",
	    				box : isDrawBox,
	    				onSelect : this.SelectedFeatureSuCo,
	    				onUnselect: this.UnselectFeatureSuCo
	    			});
	    	map.addControl(ScanFeature.control);    	
	    	ScanFeature.control.activate();
	    },
	    /** unselect feature action */
	    UnselectFeatureSuCo1:function(fes)
	    {
	    	ScanFeature.remove(fes.fid);
	    },
	    /** select feature action */
	    SelectedFeatureSuCo1 : function(fes)
	    {
	    	$("#suco-content").show();
	    	if(ScanFeature.arrayFid.length == 0) $("#tbTaiSanSuCo tbody tr").remove().end();
	    	ScanFeature.insert(fes.fid);
	    	ScanFeature.setListLayer();
	    	var layer =  vectorArray[ScanFeature.indexLayer-numBaseLayer];
			//ScanFeature.display(layer.LayerId);
	    	var id = fes.attributes[getFieldColumnKey(layer.LayerId)];
	    	var tentaisan = fes.attributes[getFieldColumnName(layer.LayerId)];
	    	tentaisan = (tentaisan == undefined) ? "" : tentaisan;
	    	ScanFeature.FillDataToTableSuCo(fes,id, tentaisan);
	    },
	    FillDataToTableSuCo : function(fes, id, name){
	    	var objTbl = base.getElementById("tbTaiSanSuCo");
	    	var objTR = document.createElement("tr");
	    	objTR.style.cursor = "pointer";
	    	// checkbox
	    	var objTDChk = document.createElement("td");
	    	var objCheckbox = document.createElement("input");
	    	objCheckbox.type = 'checkbox';
	    	objCheckbox.id = 'chk_' + fes.fid;
	    	objCheckbox.name = 'chk_' + fes.fid;
	    	objCheckbox.parent = arrTRDelFeature[fes.fid] = objTR;
	    	objCheckbox.title=id;
	    	objCheckbox.setAttribute("namets", name);
	    	objCheckbox.checked =true;
	    	objTR.checkbox = objCheckbox;
	    	objTR.fid = fes.fid;
	    	$(objCheckbox).click( function(e)
	    	{
	    		ScanFeature.selectFeature_SuCo(fes,objCheckbox);
	    	});
	    	objTDChk.appendChild(objCheckbox);
	    	// add id
	    	var objTDid = document.createElement("td");
	    	$(objTDid).text(id);
	    	//add name
	    	var objTDname = document.createElement("td");
	    	$(objTDname).text(name);
	    	
	    	objTR.appendChild(objTDChk);
	    	objTR.appendChild(objTDid);
	    	objTR.appendChild(objTDname);
	    	objTbl.children[1].appendChild(objTR);
	    },
	    selectFeature_SuCo1 : function(fes, obj)
	    {
	    	if(obj.checked)
	    	{
	    		map.layers[ScanFeature.indexLayer].drawFeature(fes, "select");
	    	}
	    	else
	    	{
	    		map.layers[ScanFeature.indexLayer].drawFeature(fes, "default");
	    	}
	    },
	    onChangeSelectLayerSuCo:function(ctrl)
		{
			var south = $(".south");
			south.hide();
			ScanFeature.indexLayer = ctrl.value;
			
			if( ScanFeature.indexLayer !=0 ){
				ScanFeature.create();
				ScanFeature.SelectSuCo(ctrl.value);
			}
			else{
				if(ScanFeature.control!=null)ScanFeature.control.deactivate();
				
				var div = base.getElementById(DivObject.DIV_CONTENT_LISTASSET_BY_SELECTION);
				base.removeChildDiv(div);
			}
		},
		
		/** select polygon action */
		SelectSuCo : function(indexLayer)
	    {
	    	MapAction.DeActive();
	    	if(ScanFeature.control!=null) map.removeControl(ScanFeature.control);
	    	if(ScanFeature.layer != null) map.destroy();
	    	var _arrayNew = null;
	    	if(indexLayer!=0)_arrayNew = map.layers[indexLayer];
	    	map.layers[indexLayer].setVisibility(true);
	    	ScanFeature.control = OpenLayers.Class(OpenLayers.Control, {
	    		_arrayNew : {
	    			'single' : true,
	    			'double' : false,
	    			'pixelTolerance' : 0,
	    			'stopSingle' : false,
	    			'stopDouble' : false
	    		},
	    		initialize : function(options) {
	    			this.handlerOptions = OpenLayers.Util.extend({},
	    					this.defaultHandlerOptions);
	    			OpenLayers.Control.prototype.initialize.apply(this, arguments);
	    			this.handler = new OpenLayers.Handler.Click(this, {
	    				'click' : this.onClick,
	    				//'dblclick' : this.onDblclick
	    			}, this.handlerOptions);
	    		},

	    		onClick : this.SelectedFeatureSuCo,
	    		//onDblclick : dbclickEvent_ModifyFeature
	    	});
	    	var clickEvent = new ScanFeature.control({
	    		handlerOptions : {
	    			"single" : true,
	    		}
	    	});
	    	map.addControl(clickEvent);
	    	clickEvent.activate();
	    },
	    
	    /** select feature action */
	    SelectedFeatureSuCo : function(evt)
	    {
	    	$("#suco-content").show();
	    	var Coordinate = map.getLonLatFromPixel(evt.xy);
	    	var tolerance = base.getDeltaOnMap(map);
	    	var bounds = new OpenLayers.Bounds(Coordinate.lon - tolerance,
	    			Coordinate.lat - tolerance, Coordinate.lon + tolerance,
	    			Coordinate.lat + tolerance);
	    	// remove and add feature de lay geometry
	    	createPolygonFromBound(vectorGraphicsClick, bounds);
	    	//var pointClick = new OpenLayers.Geometry.Point(Coordinate.lon, Coordinate.lat);
	    	//var indexLayer = LayerTool.getIndexLayer();
	    	var indexLayer = $("#select_Tool_cboLayers_geom").val();
			var layerActivate = null;
			
			layerActivate = map.layers[indexLayer];
			if(ScanFeature.oldFeature != null) layerActivate.drawFeature(ScanFeature.oldFeature, "default");
			var bPolyline = false;
			if(vectorArray[indexLayer].Geometry_Type.toLowerCase() == Geometries.Polyline.toLowerCase()) bPolyline = true;
			var line = null;
			if(bPolyline)
			{			
				tolerance = 10;
				var pPoint1 = new OpenLayers.Geometry.Point();
				pPoint1.x = Coordinate.lon - tolerance;
				pPoint1.y = Coordinate.lat - tolerance;
				var pPoint2 = new OpenLayers.Geometry.Point();
				pPoint2.x = Coordinate.lon + tolerance;
				pPoint2.y = Coordinate.lat + tolerance;
				var pointList = [];
				pointList.push(pPoint1);
				pointList.push(pPoint2);
				line = new OpenLayers.Geometry.LineString(pointList);
			}
			var feature = null;
			var i = 0, j = 0;
			for (i = 0; i < layerActivate.features.length; i++) {
				var objFeature = layerActivate.features[i];
				if(bPolyline)
				{			
					// line
					if(objFeature.geometry.componentTypes[0] == "OpenLayers.Geometry.LineString")
					{
						if(objFeature.geometry.intersects(line))
						{
							layerActivate.drawFeature(objFeature, "select");
							feature = objFeature;
							break;
						}
					}
					// multi line
					else
					{
						for(j=0;j<objFeature.geometry.components.length; j++)
						{
							var objComponents = objFeature.geometry.components[j];
							if(objComponents.intersects(line))
							{
								layerActivate.drawFeature(objFeature, "select");
								feature = objFeature;
								break;
							}
						}
					}
				}
				else
				{
					var b = objFeature.geometry.bounds;
					var bb = null;
					// neu doi tuong la point
					if (parseFloat(b.left) == parseFloat(b.right)) {
						bb = new OpenLayers.Bounds(b.left - tolerance, b.bottom - tolerance,
								b.right + tolerance, b.top + tolerance);
					    
						if (bounds.intersectsBounds(bb)) {
							layerActivate.drawFeature(objFeature, "select");
							feature = objFeature;
							break;
						}
					}
					else 
					{
						// multy polygon -> polygon
						bb = objFeature.geometry.components[0];						    
						if (bb.intersects(vectorGraphicsClick.features[0].geometry)) {
							layerActivate.drawFeature(objFeature, "select");
							feature = objFeature;				    
							break;
						}
					}
				}
			}
			ScanFeature.oldFeature = feature;
			var layerid = feature.fid.split(".")[0];
			var id = feature.attributes[getFieldColumnKey(layerid)];
	    	var tentaisan = feature.attributes[getFieldColumnName(layerid)];
	    	tentaisan = (tentaisan == undefined) ? "" : tentaisan;
	    	$("#txtMataisan").val(id);
	    	$("#txtTentaisan").val(tentaisan);
	    	if(feature.attributes['maquan'] != undefined){
	    		$("#ddlQuan").val(feature.attributes['maquan']);
	    		$("#ddlQuan").attr('disabled','disabled');
	    		changeQuan(feature.attributes['maquan']);
	    	}else $("#ddlQuan").removeAttr("disabled");
	    	if(feature.attributes['maphuong'] != undefined){
	    		$("#ddlPhuong").val(feature.attributes['maphuong']);
	    		$("#ddlPhuong").attr('disabled','disabled');
	    		//changePhuong(feature.attributes['matuyenduong']);
	    	}else $("#ddlPhuong").removeAttr("disabled");
	    	if(feature.attributes['matuyenduong'] != undefined && feature.attributes['matuyenduong'] != ""){
	    		$("#ddlTuyenDuong").val(feature.attributes['matuyenduong']);
	    		$("#ddlTuyenDuong").attr('disabled','disabled');
	    	}else {
	    		$("#ddlTuyenDuong").removeAttr("disabled");
	    	}
	    	$("#ddlQuan").uniform();
	    	$("#ddlPhuong").uniform();
	    	$("#ddlTuyenDuong").uniform();
	    	var date = new Date();
	    	$("#txtNgayPhatHien").val(date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear());
	   }
};

function changeQuan(idquan){
	$.ajax({
		type : "post",
		url : "/NhaTrangGis-portlet/html/drainwater/GetData.jsp",
		data : {
			attr : "getmaphuongbymaquan",
			maquan : idquan
		},
		async : false,
		success : function(result) {
			$("#ddlPhuong").html(result.trim());
		}, error: function() {
		}
	});
	
}

function changePhuong(idPhuong){
	$.ajax({
		type : "post",
		url : "/NhaTrangGis-portlet/html/drainwater/GetData.jsp",
		data : {
			attr : "gettuyenduongbymaphuong",
			maphuong : idPhuong
		},
		async : false,
		success : function(result) {
			$("#ddlTuyenDuong").html(result.trim());
		}, error: function() {
		}
	});
}

